package com.inspur.dgov.bsp.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inspur.dgov.bsp.user.entity.PubUser;
import com.inspur.dgov.bsp.user.entity.PubUserRole;
import com.inspur.dgov.bsp.user.mapper.PubUserMapper;
import com.inspur.dgov.bsp.user.service.PubUserRoleService;
import com.inspur.dgov.bsp.user.service.PubUserService;
import com.inspur.dgov.bsp.user.vo.UserVO;
import com.inspur.dgov.common.tool.utils.UniqueIdGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户信息 服务实现类
 *
 * @author chiyupei
 * @version 1.0
 * @since 1.0
 */
@Slf4j
@Service
@AllArgsConstructor
public class PubUserServiceImpl extends ServiceImpl<PubUserMapper, PubUser> implements PubUserService {

    private PubUserRoleService pubUserRoleService;

    /**
     * 用户信息分页数据
     * @param page
     * @param params
     * @return
     */
    @Override
    public IPage<UserVO> selectUserPage(Page page, Map<String, Object> params) {
        return baseMapper.selectUserPage(page, params);
    }

    /**
     * 用户信息
     * @param user
     * @return
     */
    @Override
    public UserVO getUserInfo(PubUser user) {
        return baseMapper.getUserInfo(user);
    }

    /**
     * 用户角色权限配置
     *
     * @param roleIds 角色id集合
     * @param userId 用户id
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean grant(String roleIds, String userId) {
        // 删除用户配置的角色集合
        this.pubUserRoleService.remove(Wrappers.<PubUserRole>update().lambda().eq(PubUserRole::getUserId, userId));
        // 组装配置
        List<PubUserRole> userRoles = new ArrayList<>();
        List<String> list = StrUtil.split(roleIds, ',');
        list.forEach(roleId -> {
            PubUserRole userRole = new PubUserRole();
            userRole.setId(UniqueIdGenerator.generateId());
            userRole.setRoleId(Long.valueOf(roleId));
            userRole.setUserId(Long.valueOf(userId));
            userRoles.add(userRole);
        });
        // 新增配置
        return this.pubUserRoleService.saveBatch(userRoles);
    }
}
